# -*- coding: utf-8 -*-
# from odoo import api, fields, models,_
from odoo.exceptions import AccessError, UserError, ValidationError
from passlib.context import CryptContext
import os
import hashlib
import json
import logging
from odoo import api, http, models,fields,_
from odoo.http import request
from odoo.tools import file_open, image_process, ustr
from odoo.tools.misc import str2bool
import re
import odoo.addons.decimal_precision as dp
import logging
import base64
_logger = logging.getLogger(__name__)
# import numpy as np

# WORKTYPE_SELECTION=[('A1','数值'),('A2','判断'),('A3','输入'),('A4','统计')]
WORKTYPE_SELECTION=[('A1','数值'),('B2','判断'),('B3','输入'),('A4','统计')]
class MeasWorkMain(models.Model):
    _name="meas.work.main"
    _description="工单表头"
    _rec_name="name"
    _order="sequence"
    _inherit = ['barcodes.barcode_events_mixin']

    main_id=fields.Many2one('meas.main',string='工序单号')
    name = fields.Char(string="工序单号",related="main_id.name",store=True)
    title=fields.Char(string='工序名称',related='main_id.title',store=True)
    require=fields.Text('工艺要求',related='main_id.require',store=True)    
    sequence=fields.Integer('序列号')
    meas_id=fields.Many2one('meas.meas',string='机型模板',related="main_id.meas_id",store=True)
    meas_name=fields.Char('机型',related="meas_id.name",store=True)
    work_sub_ids=fields.One2many('meas.work.sub','work_main_id',string='工单明细')
    # company_id = fields.Many2one('res.company',string="组织")
    company_id = fields.Many2one('res.company',string="组织",related="main_id.company_id")
    operator_id = fields.Many2one('res.users', default=lambda self: self.env.user.id)
    document_image=fields.Image(string="图片文件",related="main_id.document_image")
    document_image2=fields.Image(string="图片文件",related="main_id.document_image2")
    document_image3=fields.Image(string="图片文件",related="main_id.document_image3")
    ref=fields.Char('工艺卡号',related='main_id.ref')
    prd_id=fields.Many2one('meas.prd','机号',related="main_id.prd_id",store=True)
    prd_num=fields.Char(string='编号',related="main_id.prd_num",store=True)
    # prd_name=fields.Char(string='机型',related="main_id.prd_name",store=True)
    direction=fields.Selection(string='方向',related="main_id.direction",store=True )
    # tool_id=fields.Many2one('meas.tool.info',related="main_id.tool_id",string='选用量具',readonly=False)
    ref_tool_ids=fields.Many2many('meas.tool.info',related="main_id.tool_ids",string='参考量具')
    tool_ids=fields.Many2many('meas.tool.info',string='选用量具')
    no_pass=fields.Boolean("不放行")
    # signature=fields.Image(string="签字")
    key=fields.Boolean('关键标识',related="main_id.key")
    key_image=fields.Binary(string="关键标识图",attachment=True,related="main_id.key_image")
    # no_tools=fields.Boolean('未选量具',compute="_compute_no_tools")
    # barcodestr=fields.Char('二维码字符串')
    permit_user_ids=fields.Many2many('res.users',string="允许操作人员",related="main_id.permit_user_ids")
    temp=fields.Selection(string='模板',related='main_id.temp',store=True)
    pass_allow=fields.Float('允许误差',digits='Meas of Unit',related ="main_id.pass_allow")
    pass_flag=fields.Boolean('实际甩挡差之差',default=False)
    max_temperature=fields.Integer('最大温度°C',related="main_id.max_temperature")
    max_humidity=fields.Integer('最大湿度%',related="main_id.max_humidity")
    real_temperature=fields.Integer('实际温度°C')
    real_humidity=fields.Integer('实际湿度%')

    # @api.depends('tool_ids')
    # def _compute_no_tools(self):
    #     for r in self:
    #         # r.no_tools=not bool(len(r.tool_ids))

    #         # 测试
    #         r.no_tools=False
    
    # @api.onchange('barcodestr')
    # def _onchange_barcodestr(self):
        #当扫码的数据最后一位是},即可进行处理。否则需要加;等待下一个二维码
        # if self.barcodestr[-1]=="}":
        #     barcode=self.barcodestr.split(';')
        #     id_list=[]
        #     for d in barcode:
        #         try:
        #             data=json.loads(d)
        #         except:
        #             raise ValidationError('分割符不是英文的;!')    
        #         if self.key:
        #             if data['key'] and len(self.env['meas.tool.info'].search([('id','=',data['id'])]))!=0:
        #                 id_list.append(int(data['id']))
        #         else:
        #             if not data['key'] and len(self.env['meas.tool.info'].search([('id','=',data['id'])]))!=0:
        #                 id_list.append(int(data['id']))        
        #     self.tool_ids=[(6,0,id_list)]
        #     self.barcodestr=None
        # pass

    #启动这个模型，修改字段的属性
    @api.model
    def fields_get(self,allfields=None,attributes=None):
        res = super(MeasWorkMain, self).fields_get(allfields=allfields,attributes=attributes)
        #判断当前登录用户是否是管理员，如果不是则将其字段改成自读属性，否则可以修改其放行
        if 'no_pass' in res:
            if not self.user_has_groups('meas.group_meas_pass'):
                res['no_pass']['readonly']=True
            else:
                res['no_pass']['readonly']=False
        return res
                
    # def upto_meas_data(self):
    #     active_list=self.env.context.get('active_ids',self.ids)
    #     active_model=self.env.context.get('active_model',self._name)
    #     company_id=self.env.company.id
    #     #工单选中后动作中会出现上传数据，下面获取已经通个的所有数据并建立字典列表,在meas.data执行create创建数据：
    #     # active_model: meas.work.main
    #     records=self.env[active_model].search([('id','in',active_list),('no_pass','=',False),('company_id','=',company_id)])
    #     # records=self.env[active_model].search([('id','in',active_list),('company_id','=',company_id)])
    #     vals_list=[]    
    #     for r in records:    
    #         for rec in r.work_sub_ids:
    #             #解决json不能直接传二进制文件
    #             if r.signature:
    #                 signature=str(base64.b64encode(r.signature),'utf-8')
    #             else:
    #                 signature=None    
    #             if rec.photo:
    #                 photo=str(base64.b64encode(rec.photo),'utf-8')
    #             else:
    #                 photo=None    
    #             vals_list.append({
    #             'meas_main_sub_id':rec.meas_main_sub_id.id,
    #             'operator_id':rec.operator_id.id,
    #             'company_id':rec.company_id.id,
    #             'datetime_work':rec.datetime_work or fields.Datetime.now(),
    #             'result':rec.result,
    #             'check':rec.check,
    #             'real_value':rec.real_value,
    #             'real_value2':rec.real_value2,
    #             # 'tool_ids':[(6,0,r.tool_ids.ids)],
    #             'meas_main_id':r.main_id.id,
    #             'signature':signature,
    #             'photo':photo,
    #             'permit_user_ids':r.permit_user_ids,
    #             'no_pass':rec.no_pass

    #             })
    #     self.env['meas.data'].sudo().create(vals_list)    
    #     return

class MeasWorkSub(models.Model):
    _name="meas.work.sub"
    _description="工单明细"
    _rec_name="number"
    _order="sequence"

    work_main_id=fields.Many2one('meas.work.main',ondelete='cascade')
    datetime_work=fields.Datetime('操作时间')
    meas_main_sub_id=fields.Many2one('meas.main.sub',string="工序节点号")
    meas_main_id=fields.Many2one('meas.main',string='工序单号',related="meas_main_sub_id.main_id",store=True)
    number = fields.Char('节点',related="meas_main_sub_id.number")
    worktype_selection=fields.Selection(string='类型',related="meas_main_sub_id.worktype_selection",store=True)
    position_id=fields.Many2one('meas.position',string='位置',related="meas_main_sub_id.position_id",store=True)
    sequence=fields.Integer(string='顺序号',related="meas_main_sub_id.sequence",store=True)
    target_value=fields.Float(string="目标值(3)",digits='Meas of Unit',related="meas_main_sub_id.target_value")
    value_unit=fields.Selection(string='单位',related="meas_main_sub_id.value_unit")
    min_value=fields.Float(string='下值公差(3)',digits='Meas of Unit',related="meas_main_sub_id.min_value")
    max_value=fields.Float(string='上值公差(3)',digits='Meas of Unit',related="meas_main_sub_id.max_value")
    # allow=fields.Float(string='误差范围(3位):',digits='Meas of Unit',related="meas_main_sub_id.allow")
    target_value2=fields.Float(string="目标值",digits='two of Unit',related="meas_main_sub_id.target_value2")
    min_value2=fields.Float(string='下值公差',digits='two of Unit',related="meas_main_sub_id.min_value2")
    max_value2=fields.Float(string='上值公差',digits='two of Unit',related="meas_main_sub_id.max_value2")
    # target_angle2=fields.Float('角度',digits='two of Unit',related="meas_main_sub_id.target_angle2")
    min_angle2=fields.Float('最小角度',digits='two of Unit',related="meas_main_sub_id.min_angle2")
    max_angle2=fields.Float('最大角度',digits='two of Unit',related="meas_main_sub_id.max_angle2")
    # target_angle=fields.Float('角度(3)',digits='Meas of Unit',related="meas_main_sub_id.target_angle")
    min_angle=fields.Float('最小角度(3)',digits='Meas of Unit',related="meas_main_sub_id.min_angle")
    max_angle=fields.Float('最大角度(3)',digits='Meas of Unit',related="meas_main_sub_id.max_angle")
    # allow2=fields.Float(string='误差范围(2位):',default=0.05,digits='two of Unit',related="meas_main_sub_id.allow2")
    remark=fields.Char("说明",related="meas_main_sub_id.remark")
    operator_id = fields.Many2one('res.users',string='操作员')
    company_id = fields.Many2one('res.company',string="组织",related="work_main_id.company_id",store=True)
    decimal=fields.Boolean('小数点三位',related="meas_main_sub_id.decimal")
    result=fields.Text('输入')
    check=fields.Boolean('判断')
    real_value=fields.Float('实测数据(3位)',digits="Meas of Unit")
    real_value2=fields.Float('实测数据(2位)',digits="two of Unit")
    real_angle2=fields.Float('实测角度',digits='two of Unit')
    # tool_id=fields.Many2one('meas.tool.info',string='选用量具',related="work_main_id.tool_id",store=True)
    # worktype_value=fields.Char('导出数据显示值',related="meas_main_sub_id.worktype_value")
    require=fields.Text('工艺要求',related="work_main_id.require")
    ref=fields.Char('工艺卡号',related="work_main_id.ref")
    # document_image=fields.Image(string="图片文件",related="work_main_id.document_image")
    # document_image2=fields.Image(string="图片文件",related="work_main_id.document_image2")
    # document_image3=fields.Image(string="图片文件",related="work_main_id.document_image3")
    meas_id=fields.Many2one('meas.meas',string='机型',related='meas_main_id.meas_id')
    # prd_name=fields.Char('机型',related="work_main_id.prd_name")
    no_pass=fields.Boolean('不放行',compute="_compute_no_pass",store=True)
    prd_id=fields.Many2one(string='机号',related="work_main_id.prd_id",store=True)
    prd_num=fields.Char(string='编号',related="work_main_id.prd_num",store=True)
    grp=fields.Selection(string='组',related="meas_main_sub_id.grp",store=True)
    flag=fields.Integer(string='标志位',related="meas_main_sub_id.flag")
    # signature=fields.Image(string="签字",max_width=128,max_height=128,related="work_main_id.signature",store=True)
    photo=fields.Image(string="照片",max_width=128,max_height=128 )
    key=fields.Boolean('关键标识',related="work_main_id.key",store=True)
    key_image=fields.Binary(string="关键标识图",attachment=True,related="work_main_id.key_image")
    # no_tools=fields.Boolean('未选量具',related="work_main_id.no_tools")
    deviceId=fields.Char('蓝牙设备的ID')
    check_value=fields.Float('复测数据(3位)',digits="Meas of Unit")
    check_value2=fields.Float('复测数据(2位)',digits="two of Unit")
    dv=fields.Float('实际误差dv',digits="Meas of Unit")
    dh=fields.Float('实际误差dh',digits="Meas of Unit")
    ref_image=fields.Image(string="参考图",related="meas_main_sub_id.ref_image")

    
    def collect_action(self):
        action = {
                'name': '采集数据',
                'res_model': 'meas.work.sub.wizard',
                'type': 'ir.actions.act_window',
                'view_mode': 'form',
                'views': [[self.env.ref('meas.collection_form_wizard').id, 'form']],
                'target': 'new',
            }
        return action    

    @api.depends('real_value','real_value2','result','check')
    def _compute_no_pass(self):
        work_main_id=self.work_main_id
        no_pass_list=[]
        ids=work_main_id.work_sub_ids.ids
        for i in ids:
            r=self.env['meas.work.sub'].browse(i)
            r.no_pass=True
            # if r.worktype_selection == 'A1' and r.operator_id and not r.no_tools:
            if r.worktype_selection == 'A1' and r.operator_id:
                if r.real_value:
                    if r.real_value >= r.min_value and r.real_value <=r.max_value:
                        r.no_pass=False
                    else:
                        r.no_pass=True
                elif r.real_value2:
                    if r.real_value2 >= r.min_value2 and r.real_value2 <=r.max_value2:
                        r.no_pass=False
                    else:
                        r.no_pass=True

            if r.worktype_selection == 'A2':
                    r.no_pass=not r.operator_id    
            if r.worktype_selection == 'A3' and r.operator_id:
                if r.result:
                    r.no_pass=False
                else:
                    r.no_pass=True
            # if r.worktype_selection == 'A4' and r.operator_id and not r.no_tools:
            if r.worktype_selection == 'A4' and r.operator_id:
                # if r.compute >= r.min_value and r.compute <= r.max_value:
                if r.real_value:
                    if r.real_value >= r.min_value and r.real_value <= r.max_value:
                        r.no_pass=False
                    else:
                        r.no_pass=True
                elif r.real_value2:
                    if r.real_value2 >= r.min_value2 and r.real_value2 <= r.max_value2:
                        r.no_pass=False
                    else:
                        r.no_pass=True
            no_pass_list.append(r.no_pass)
        work_main_id.no_pass=any(no_pass_list)    
        return

    def write(self,val):
        val['operator_id']=self.env.user.id
        val['datetime_work']=fields.Datetime.now()
        super().write(val)
    
    #改成由工单上传而非工单明细上传
    # def to_meas_data(self):
    #     active_list=self.env.context.get('active_ids',self.ids)
    #     active_model=self.env.context.get('active_model',self._name)
    #     company_id=self.env.company.id
    #     #工单选中后动作中会出现上传数据，下面获取已经通个的所有数据并建立字典列表,在meas.data执行create创建数据：
    #     records=self.env[active_model].sudo().search([('no_pass','=',False),('company_id','=',company_id)])
    #     vals_list=[]    
    #     for r in records:    
    #         vals_list.append({
    #             'meas_main_sub_id':r.meas_main_sub_id.id,
    #             'operator_id':r.operator_id.id,
    #             'datetime_work':r.datetime_work or fields.Datetime.now(),
    #             'result':r.result,
    #             'check':r.check,
    #             'real_value':r.real_value,
    #             'tool_id':r.tool_id.id
    #         })
    #     self.env['meas.data'].create(vals_list)    
    #     return

    # @api.depends("compute_ids")
    # def _compute_compute(self):
    #     for r in self:
    #         if r.worktype_selection == 'A4' and r.compute_ids:
    #             i=0
    #             value=0.000
    #             for rec in r.compute_ids:
    #                 if rec.value != 0:
    #                     i=i+1
    #                     value= value + rec.value
    #             if i !=0:        
    #                 # r.compute=value/i
    #                 r.real_value=value/i
    #             else:
    #                 # r.compute=0
    #                 r.real_value=0
